package com.ympc.controller;

import com.ympc.pojo.Assignment;
import com.ympc.pojo.AssignmentVO;
import com.ympc.pojo.Class;
import com.ympc.pojo.Student;
import com.ympc.pojo.StudentAssignment;
import com.ympc.pojo.Teacher;
import com.ympc.pojo.Users;
import com.ympc.service.AssignmentService;
import com.ympc.service.ClassService;
import com.ympc.service.StudentAssignmentService;
import com.ympc.service.StudentService;
import com.ympc.service.TeacherService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

/**
 * 学生作业控制器
 */
@Controller
@RequestMapping("/student/assignment")
public class StudentAssignmentController {
    
    @Resource
    private StudentAssignmentService studentAssignmentService;
    
    @Resource
    private AssignmentService assignmentService;
    
    @Resource
    private StudentService studentService;
    
    @Resource
    private TeacherService teacherService;
    
    @Resource
    private ClassService classService;
    
    /**
     * 任务提醒 - 显示所有作业列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String assignmentList(HttpSession session, Model model) {
        try {
            Users user = (Users) session.getAttribute("user");
            if (user == null) {
                return "redirect:/";
            }
            
            // 根据userId获取学生信息
            Student student = null;
            try {
                student = studentService.getStudentByUserId(user.getId());
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("获取学生信息时出错：" + e.getMessage());
                model.addAttribute("error", "获取学生信息时出错：" + e.getMessage());
                return "student/assignment/list";
            }
            
            if (student == null) {
                model.addAttribute("error", "学生信息不存在，请联系管理员。用户名：" + user.getUsername());
                model.addAttribute("assignments", new java.util.ArrayList<>());
                return "student/assignment/list";
            }
            
            // 将学生信息添加到session，以便在所有页面使用
            session.setAttribute("student", student);
            
            // 获取该学生的所有作业（根据学生班级）
            List<Assignment> assignments = new java.util.ArrayList<>();
            try {
                // 使用Service方法获取该学生的作业
                assignments = studentAssignmentService.getAssignmentsForStudent(student.getId());
                if (assignments == null) {
                    assignments = new java.util.ArrayList<>();
                }
                
                // 获取该学生已提交的作业ID列表
                List<StudentAssignment> submissions = new java.util.ArrayList<>();
                try {
                    submissions = studentAssignmentService.getSubmittedAssignments(student.getId());
                    if (submissions == null) {
                        submissions = new java.util.ArrayList<>();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("获取已提交作业时出错：" + e.getMessage());
                    submissions = new java.util.ArrayList<>();
                }
                
                // 转换为AssignmentVO并填充科目信息
                List<AssignmentVO> assignmentVOs = new java.util.ArrayList<>();
                for (Assignment assignment : assignments) {
                    if (assignment == null) continue;
                    
                    // 创建AssignmentVO
                    AssignmentVO assignmentVO = new AssignmentVO(assignment);
                    
                    // 标记是否已提交
                    for (StudentAssignment submission : submissions) {
                        if (submission != null && submission.getAssignmentId() != null 
                            && submission.getAssignmentId().equals(assignment.getId())) {
                            assignmentVO.setStatus("submitted"); // 标记为已提交
                            break;
                        }
                    }
                    
                    // 获取教师信息（包含科目）
                    if (assignment.getTeacherId() != null) {
                        try {
                            Teacher teacher = teacherService.getTeacherById(assignment.getTeacherId());
                            if (teacher != null) {
                                assignmentVO.setSubject(teacher.getSubject());
                                assignmentVO.setTeacherName(teacher.getRealName());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.err.println("获取教师信息时出错：" + e.getMessage());
                        }
                    }
                    
                    // 获取班级信息
                    if (assignment.getClassId() != null) {
                        try {
                            Class clazz = classService.getClassById(assignment.getClassId());
                            if (clazz != null) {
                                assignmentVO.setClassName(clazz.getClassName());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.err.println("获取班级信息时出错：" + e.getMessage());
                        }
                    }
                    
                    assignmentVOs.add(assignmentVO);
                }
                
                model.addAttribute("assignments", assignmentVOs);
                model.addAttribute("student", student);
                
                // 将学生信息添加到session，以便在所有页面使用
                session.setAttribute("student", student);
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("获取作业列表时出错：" + e.getMessage());
                e.printStackTrace();
                model.addAttribute("error", "获取作业列表时出错：" + e.getMessage());
                model.addAttribute("assignments", new java.util.ArrayList<>());
            }
            
            return "student/assignment/list";
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Controller执行时出错：" + e.getMessage());
            e.printStackTrace();
            model.addAttribute("error", "系统错误：" + e.getMessage());
            model.addAttribute("assignments", new java.util.ArrayList<>());
            return "student/assignment/list";
        }
    }
    
    /**
     * 作业详情和提交页面
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String assignmentDetail(@RequestParam Integer assignmentId, 
                                    HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Student student = studentService.getStudentByUserId(user.getId());
        if (student == null) {
            model.addAttribute("error", "学生信息不存在");
            return "redirect:/student/assignment/list";
        }
        
        // 将学生信息添加到session，以便在所有页面使用
        session.setAttribute("student", student);
        
        try {
            Assignment assignment = assignmentService.getAssignmentById(assignmentId);
            if (assignment == null) {
                model.addAttribute("error", "作业不存在");
                return "redirect:/student/assignment/list";
            }
            
            // 检查是否已提交
            StudentAssignment submission = studentAssignmentService.getSubmission(assignmentId, student.getId());
            
            model.addAttribute("assignment", assignment);
            model.addAttribute("submission", submission);
            model.addAttribute("student", student);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "获取作业详情时出错：" + e.getMessage());
            return "redirect:/student/assignment/list";
        }
        
        return "student/assignment/detail";
    }
    
    /**
     * 提交作业
     */
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public String submitAssignment(@RequestParam Integer assignmentId,
                                   @RequestParam(required = false) String content,
                                   @RequestParam(required = false) MultipartFile file,
                                   HttpSession session, Model model) {
        Users user = (Users) session.getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }
        
        Student student = studentService.getStudentByUserId(user.getId());
        if (student == null) {
            model.addAttribute("error", "学生信息不存在");
            return "redirect:/student/assignment/list";
        }
        
        try {
            StudentAssignment submission = new StudentAssignment();
            submission.setAssignmentId(assignmentId);
            submission.setStudentId(student.getId());
            submission.setContent(content);
            submission.setSubmitTime(new Date());
            submission.setStatus("submitted");
            
            // 处理文件上传
            if (file != null && !file.isEmpty()) {
                try {
                    // 使用项目根目录下的uploads文件夹
                    String uploadDir = "uploads/assignments/";
                    Path uploadPath = Paths.get(uploadDir);
                    if (!Files.exists(uploadPath)) {
                        Files.createDirectories(uploadPath);
                    }
                    
                    String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
                    String filePath = uploadDir + fileName;
                    Path destPath = uploadPath.resolve(fileName);
                    Files.copy(file.getInputStream(), destPath);
                    
                    submission.setFilePath(filePath);
                    submission.setFileName(file.getOriginalFilename());
                } catch (IOException e) {
                    e.printStackTrace();
                    model.addAttribute("error", "文件上传失败：" + e.getMessage());
                    return "redirect:/student/assignment/detail?assignmentId=" + assignmentId;
                }
            }
            
            boolean success = studentAssignmentService.submitAssignment(submission);
            if (success) {
                model.addAttribute("message", "作业提交成功");
            } else {
                model.addAttribute("error", "作业提交失败，请重试");
            }
            
            return "redirect:/student/assignment/detail?assignmentId=" + assignmentId;
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "提交作业时出错：" + e.getMessage());
            return "redirect:/student/assignment/detail?assignmentId=" + assignmentId;
        }
    }
}

